<template>
    <div class="tools-map-draw-print-page _page">
        <div class="map-container">
            <div ref="mapContainerEl" :class="{ drawing: isStarted && !isFinished }"></div>
        </div>

        <!--地块范围列表-->
        <ul class="bounds-list" v-show="pointsArr.length>1 && isStarted && !isFinished">
            <li v-for="(item, index) in pointsArr" :key="index">范围{{ index + 1 }}<a @click="doDelBound(index)" class="iconfont">&#xe659;</a></li>
        </ul>

        <!--当前地图缩放级别和面积-->
        <div class="curr-zoom">{{ currZoom }}<span v-show="currArea">{{ currArea }}亩</span><span>{{ currLatlng }}</span></div>

        <!--右侧工具按钮-->
        <Tools v-show="!isFinished" @ope="doClickTool" :canUndo="canUndo" :canClear="canClear"/>

        <!--开始圈画按钮-->
        <button class="start-button" v-show="!isStarted" @click="doStartDraw()">开始圈画</button>

        <!--完成圈画按钮-->
        <button class="finish-button" v-show="isStarted && isClosed && !isFinished" @click="doFinishDraw()">完成圈画</button>

        <!--继续编辑按钮-->
        <button class="finish-button" v-show="isStarted && isClosed && isFinished" @click="doContinueDraw()">调整圈画</button>

        <!--图层管理-->
        <Layers />
    </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { addLeaflet, addJsAndCss } from '@/lib/util'
import { init } from './util'
import Draw from './Draw.js'
import Tools from './Tools.vue'
import Layers from './layers/Main.vue'
import { useToastStore } from '@/stores/toast'
import drawConfig from './drawConfig'

export default {
    components: { Tools, Layers },
    setup () {
        const mapContainerEl = ref(null)
        let map = null
        const toast = useToastStore()
        let draw = null // 绘制类

        const currZoom = ref('') // 当前缩放级别
        const currLatlng = ref('')
        const currArea = ref('') // 当前面积 -亩
        const isStarted = ref(false) // 是否已开始
        const isClosed = ref(false) // 是否已闭合
        const canUndo = ref(false) // 是否可以撤销
        const canClear = ref(false) // 是否可以清空
        const pointsArr = ref([]) // 绘制的点数组
        const isInited = ref(false) // 是否已初始化
        const isFinished = ref(false) // 是否点了完成圈画
        let gardenLayerGroup = null // 用于放置农场范围边界

        const syncDrawFunc = (statusObj) => {
            isStarted.value = statusObj.isStarted
            isClosed.value = statusObj.isClosed
            currArea.value = statusObj.area
            canUndo.value = statusObj.canUndo
            canClear.value = statusObj.canClear
            pointsArr.value = statusObj.pointsArr
        }

        const doClickTool = (opeName) => {
            if (opeName == 'undo') {
                draw.doUndo()
            } else if (opeName == 'clear') {
                draw.init()
                const drawDatas = draw.getDrawDatas()
                console.log('clear drawDatas...', drawDatas)
                emit('commit', drawDatas)
            }
        }

        const doCancelDraw = () => { // 取消绘制
            draw.init(null, false)
        }

        const doClearDraw = () => { // 清空绘制
            draw.init(null, false)
            isStarted.value = false
            isFinished.value = false
            draw.setFinishedStatus(false)
        }

        const doStartDraw = (gardenBounds, gardenInfo) => {
            if (gardenBounds) {
                if (map.hasLayer(gardenLayerGroup)) {
                    gardenLayerGroup.removeFrom(map)
                }
                draw.init(gardenBounds)
                if (gardenBounds.length == 0) {
                    const latlng = gardenInfo.lat ? [gardenInfo.lat - 0, gardenInfo.lng - 0] : null
                    if (latlng) {
                        console.log('add red flag....', latlng)
                        L.marker(latlng, { icon: markerIcon, riseOnHover: true }).addTo(map._drawGroup)
                        // map.setView(latlng, 18)
                    }
                }
            } else {
                draw.init() // 初始化
            }
        }

        const doFinishDraw = () => {
            const checkRes = draw.doCheck()
            console.log('checkRes....', checkRes)
            if (!checkRes || !checkRes.status) {
                if (checkRes) {
                    toast.error(checkRes.msg)
                }
                return
            }
            const drawDatas = draw.getDrawDatas()
            console.log('drawDatas...', drawDatas)
            emit('commit', drawDatas)
            isFinished.value = true
            draw.setFinishedStatus(true)
        }

        const doFocusPlace = (latlng) => {
            map.setView(latlng, drawConfig.afterSearchPlaceMapZoom)
        }

        const doResize = () => {
            if (map) {
                map.invalidateSize(false)
                setTimeout(() => { map.invalidateSize(false) }, 100)
            }
        }

        const doContinueDraw = () => {
            isFinished.value = false
            draw.setFinishedStatus(false)
        }

        const doSetFinishStatus = (tag) => {
            isFinished.value = tag
            draw.setFinishedStatus(tag)
        }

        const doDelBound = (index) => {
            draw.delBound(index)
        }

        const isFinishDrawing = () => {
            return (pointsArr.value.length == 0) || (isStarted.value && isClosed.value && isFinished.value)
        }

        onMounted(async () => {
            await addLeaflet()
            map = init(mapContainerEl.value)
            if (!window.turf) {
                addJsAndCss('https://cdn.bootcdn.net/ajax/libs/Turf.js/6.5.0/turf.min.js', 'turf-js')
            }
            gardenLayerGroup = L.layerGroup() // 用于放置农场范围边界
            map.on('zoom', () => {
                currZoom.value = parseInt(map.getZoom())
            })
            map.on('mousemove', (e) => {
                currLatlng.value = e.latlng.lat + ',' + e.latlng.lng
            })
            currZoom.value = parseInt(map.getZoom())
            gardenLayerGroup.addTo(map)
            draw = new Draw(map, syncDrawFunc, true, null)
            isInited.value = true
            isFinished.value = false
        })

        onBeforeUnmount(() => {
            mapInstance.remove()
        })

        return {
            mapContainerEl,

            currZoom,
            currLatlng,
            currArea,
            isStarted,
            isClosed,
            canUndo,
            canClear,
            pointsArr,
            isInited,
            isFinished,
            isFinishDrawing,

            doResize,
            init,
            doFocusPlace,
            doStartDraw,
            doFinishDraw,
            doClickTool,
            doClearDraw,
            doCancelDraw,
            doContinueDraw,
            doSetFinishStatus,
            doDelBound
        }
    }
}
</script>

<style lang="scss">
    @use './style.scss';
</style>
